#ifndef _SOCKETTEST_
#define _SOCKETTEST_

#include <unistd.h>
#include "Core/Network/TCPSocketServer.h"
#include "Core/Network/TCPSocket.h"
#include "Core/Thread/Thread.h"
#include "Core/Thread/ThreadLauncher.h"
#include "UnitTest.h"

class SocketTest : public UnitTest
{
	static const int port = 3030;
public:
	virtual const char * GetName() const;
	virtual error Create();
	virtual error Destroy();
	virtual error Execute();

	class Server : public Thread
	{
		class RunningServerSocket;
	public:
		Server() : Thread(), m_socket()
		{
			m_socket.Bind(port);
		}

		virtual void Run()
		{
			PROFILE("Server::Run()");
			TCPSocket * pSocket;
			do
			{
				pSocket = m_socket.AcceptConnection();
			} while(pSocket==NULL);
			RunningServerSocket runningSocket(pSocket);
			runningSocket.Start();
			ThreadLauncher launcher;
			launcher.WaitFor(&runningSocket);
			delete pSocket;
		}

	private:

		class RunningServerSocket : public Thread
		{
		public:
			RunningServerSocket(TCPSocket * _pSocket) : Thread(), m_pSocket(_pSocket)
			{
			}

			virtual void Run()
			{
				PROFILE("RunningServerSocket::Run()");
				int i;
				m_pSocket->Receive(&i, sizeof(int));
			}

		private:
			TCPSocket * m_pSocket;
		};

		TCPSocketServer m_socket;
	};

private:

	Server * m_server;

};

#endif // _SOCKETTEST_
